package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServiceCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.PFile;
import com.yunduo.entity.Shop;
import com.yunduo.entity.User;
import com.yunduo.entity.vo.FileObj;
import com.yunduo.entity.vo.ShopObj;
import com.yunduo.entity.vo.ShopQuery;
import com.yunduo.entity.vo.TreeData;
import com.yunduo.module.task.DeleteFileTask;
import com.yunduo.service.PFileService;
import com.yunduo.service.ShopService;
import com.yunduo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  店铺控制类
 * </p>
 *
 * @author ChengXin
 * @since 2023-07-12
 */
@RestController
@RequestMapping("/shop")
public class ShopController {
    @Resource
    private ShopService shopService;
    @Resource
    private UserService userService;
    @Resource
    private PFileService pFileService;
    //查询
    @GetMapping("/getShop/{id}")
    public CommonReturn getShop(@PathVariable("id") String id){
        Shop shop = shopService.getById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("shop",shop);
    }

    //查询多个
    @PostMapping("/getShops")
    public CommonReturn getShops(@RequestBody String[] ids){
        if(ids == null || ids.length == 0){
            return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",null);
        }
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Shop::getId,ids);
        List<Shop> list = shopService.list(queryWrapper);
        list.forEach(item ->{
            User user = userService.getById(item.getOwner());
            item.setOwner(user.getName());
        });
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //修改
    @PostMapping("/updateShop")
    public CommonReturn updateShop(@RequestBody Shop shop ){
        if(StringUtils.isEmpty(shop.getId())){
            return CommonReturn.ERROR(ResultCode.ERROR).setMessage("参数错误");
        }
        boolean isUpdate = shopService.updateById(shop);
        if(!isUpdate){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //添加
    @PostMapping("/addShop")
    public CommonReturn addShop(@RequestBody @Valid ShopObj shopObj){
        Shop shop = new Shop();
        shop.setOwner(shopObj.getOwner());
        shop.setName(shopObj.getName());
        shop.setCover(shopObj.getCover());
        shop.setDescription(shopObj.getDescription());
        shop.setPop(new Integer(0));
        User user = userService.getById(shop.getOwner());
        if(null == user){
            return CommonReturn.ERROR(ResultCode.ERROR).setMessage(UserCode.USER_IS_DELETE.getInfo());
        }
        Shop isExist = shopService.getOne(new LambdaQueryWrapper<Shop>().eq(Shop::getName,shop.getName()));
        if(isExist != null){
            return CommonReturn.ERROR(ServiceCode.IS_EXIST);
        }
        boolean save = shopService.save(shop);
        if(!save){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("shop",shop);
    }

    //删除
    @PostMapping("/deleteShop")
    public CommonReturn deleteShop(String id){
        Shop shop = shopService.getById(id);
        boolean isFileDelete = true;
        if(null != shop && !StringUtils.isEmpty(shop.getCover())){
            isFileDelete = pFileService.removeByUrl(shop.getCover());
        }
        boolean isDelete = shopService.removeById(id);
        if(!isDelete && !isFileDelete){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //店铺分页查询
    @PostMapping("/pageShop")
    public CommonReturn getShopByPageQuery(@RequestBody ShopQuery query){
        Page<Shop> page = new Page<>(query.getCurrentPage(),query.getPageItems());
        LambdaQueryWrapper<Shop> userQuery = new LambdaQueryWrapper<>();
        userQuery.likeRight(!StringUtils.isEmpty(query.getName()),Shop::getName,query.getName());
        userQuery.eq(!StringUtils.isEmpty(query.getOwner()),Shop::getOwner,query.getOwner());
        if(query.getCreateBegin() != null){
            LocalDateTime begin = YunDuoUtils.splitDateString(query.getCreateBegin());
            userQuery.ge(Shop::getGmtCreate,begin);
        }
        if(query.getCreateEnd() != null){
            LocalDateTime end = YunDuoUtils.splitDateString(query.getCreateEnd());
            userQuery.le(Shop::getGmtCreate,end);
        }
        shopService.page(page,userQuery);
        List<Shop> records = page.getRecords();
        Iterator<Shop> shopIterator = records.iterator();
        while (shopIterator.hasNext()){
            Shop next = shopIterator.next();
            User owner = userService.getById(next.getOwner());
            next.setOwner(owner.getName());
        }
        HashMap<String,Object> shopList = new HashMap<>();
        shopList.put("list",records);
        shopList.put("listSize",records.size());
        shopList.put("total",page.getTotal());
        shopList.put("current",page.getCurrent());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS,shopList);
    }

    //批量店铺删除
    @DeleteMapping("/deleteShops")
    public CommonReturn deleteShops(@RequestBody String[] ids){
        boolean isDelete = shopService.removeByIds(Arrays.asList(ids));
        if(!isDelete){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //店铺列表
    @GetMapping("/getAll")
    public CommonReturn getAllShops(){
        List<Shop> list = shopService.list(new LambdaQueryWrapper<>());
        List<TreeData> shops = new ArrayList<>();
        list.forEach(item -> shops.add(new TreeData(item.getId(),item.getName(),null)));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",shops);
    }
}
